package dao.jpa;

import dao.DisciplinaDAO;
import java.util.List;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import modelo.Curso;
import modelo.Disciplina;
import util.JPAUtil;

/**
 *
 * @author Jorge
 */
public class DisciplinaJpaDAO extends AbstractJpaDao<Disciplina, Long> implements DisciplinaDAO {

    public DisciplinaJpaDAO() {
        super(Disciplina.class);
    }

    @Override
    public List<Disciplina> getAll() {
        return JPAUtil.getEntityManager().createQuery("from Disciplina").getResultList();
    }

    @Override
    public Disciplina getPorId(Long id) {
        String s = "select d from Disciplina d where d.id=?";
        Query query = JPAUtil.getEntityManager().createQuery(s);
        query.setParameter(1, id);

        try {
            return (Disciplina) query.getSingleResult();
        }
        catch (NoResultException e) {
            return null;
        }
    }

    @Override
    public List<Disciplina> getPorNome(String nome) {
        String s = "select d from Disciplina d where upper(d.nome) like upper(?)";
        Query query = JPAUtil.getEntityManager().createQuery(s);
        query.setParameter(1, "%" + nome + "%");

        return query.getResultList();
    }

    @Override
    public List<Disciplina> getDisponiveisPorCurso(Curso curso) {
        String s = "select d from Disciplina d where d not in " +
                "(select cd.disciplina from CursoDisciplina cd where cd.curso=?)";
        Query query = JPAUtil.getEntityManager().createQuery(s);
        query.setParameter(1, curso);

        return query.getResultList();
    }

    @Override
    public Disciplina getPorIdComTurmas(Long id) {
        String s = "select d from Disciplina d " +
                "left outer join fetch d.turmas dt " +
                "where d.id=?";
        Query query = JPAUtil.getEntityManager().createQuery(s);
        query.setParameter(1, id);

        return (Disciplina) query.getSingleResult();
    }

    @Override
    public List<Disciplina> getListaCompletaOrdenadaPorNome() {
        String s = "select d from Disciplina d " +
                "order by d.nome ";
        Query query = JPAUtil.getEntityManager().createQuery(s);

        return query.getResultList();
    }
}
